import {TYPES} from '../reduces/menuReduces';
import Http from '../../../utils/http';
const http = new Http();
import {Toast} from 'antd-mobile-rn';
import {i18n} from '../../../i18n/index';
import {path2base64} from '../../../utils/file2base64';
import {Alert} from 'react-native';
import _ from 'lodash';

export function loadcategorylist(isForce = false){
    return (dispatch,getState)=>_load(dispatch,getState,isForce);
}

function _load(dispatch,getState,isForce){
    let {menu} = getState();
    if(menu.categorylist.length > 0 && !isForce){
        return;
    }
    dispatch({
        type:TYPES.CHANGECATEGORYLOADING,
        categoryload:true
    })
    http.post("categorylist")
    .then((res)=>{
        if(res.status){
            dispatch({
                type:TYPES.GETCATEGORYLIST,
                categorylist:res.data.categories
            })
        }else{
            dispatch({
                type:TYPES.CHANGECATEGORYLOADING,
                categoryload:false
            })
            Toast.info(res.message,3,null,false);
        }
    })
    .catch(()=>{
        dispatch({
            type:TYPES.CHANGECATEGORYLOADING,
            categoryload:false
        })
    })
}

export function categoryInput(key,value){
    return (dispatch,getState)=>{
        let {showCategory} = getState().menu;
        showCategory[key] = value;
        dispatch({
            type:TYPES.SETCATEGORYINFO,
            showCategory
        })
    }
}

export function savaCategory(fn){
    return (dispatch,getState)=>{
        let {showCategory,categoryadding} = getState().menu;
        if(categoryadding){
            return;
        }
        let body = {}
        //edit
        if(showCategory.server_category_id){
            body.category_id = showCategory.server_category_id;
            body.version =showCategory.version + 1;
            body.image = null;
        }else{
            body.version = 1;
            if(!showCategory.path){
                return toast(i18n.t("office.menu.form.image"));
            }else{
                body.image = showCategory.path.image;
            }
        }
        if(showCategory.name == ""){
            return toast(i18n.t("office.menu.form.name"));
        }
        body.name = showCategory.name;
        body.name2 = showCategory.name2;
        // if(showCategory.description == ""){
        //     return toast(i18n.t("office.menu.form.description"));
        // }
        body.description = showCategory.description;
        if(showCategory.sort_order == "" && /^\d$/.test(showCategory.sort_order)){
            return toast(i18n.t("office.menu.form.sortorder"));
        }
        body.sort_order = showCategory.sort_order;
        console.log(body);
        dispatch(adding(true));
        http.post("categorysave",body)
        .then(res=>{
            dispatch(adding(false));
            if(res.status){
                dispatch({
                    type:TYPES.INITSHOWCATEGORY,
                })
                _load(dispatch,getState,true);
                fn && fn(true);
            }
            toast(res.message);
        })
        .catch(e=>{
            console.log(e);
            toast(i18n.t("net.neterror"))
            dispatch(adding(false));
        })
    }
} 

export function setDefaultCotegory(){
    return (dispatch,getState)=>{
        dispatch({
            type:TYPES.INITSHOWCATEGORY,
        })
    }
}

export function setCategoryInfo(showCategory){
    return (dispatch,getState)=>{
        dispatch({
            type:TYPES.SETSHOWCATEGORY,
            showCategory
        })
    }
}

export function showToast(msg = "未知"){
    return ()=>{
        toast(msg);
    }   
}

export function changeLoading(loading){
    return (dispatch,getState)=>{
        dispatch(loadingAction(loading))
    }
}

function loadingAction(loading){
    return {
        type:TYPES.CHANGELOADING,
        loading
    }
}

export function deleteCategory(item){
    return (dispatch,getState)=>{
        dispatch(loadingAction(true))
        http.post("categorydelet",{
            category_id:item.server_category_id
        })
        .then((res)=>{
            dispatch(loadingAction(false))
            if(res.status){
                _load(dispatch,getState,true);
            }
            toast(res.message);
        })
        .catch((e)=>{
            dispatch(loadingAction(false))
            toast(i18n.t("net.neterror"))
        })
    }
}

function toast(msg){
    Toast.info(msg,3,null,false);
}

function adding(categoryadding){
    return {
        type:TYPES.CHANGECATEGORYADDING,
        categoryadding
    }
}

export function getProductList(isForce = false){
    return (dispatch,getState)=>{
        _loadProduct(dispatch,getState,isForce)
    }
}

function _loadProduct(dispatch,getState,isForce){
    let {menu} = getState();
    if(menu.pruductlist.length > 0 && !isForce){
        return;
    }
    dispatch({
        type:TYPES.CHANGEPRODUCTLOADING,
        productload:true
    })
    http.post("productlist")
    .then((res)=>{
        if(res.status){
            let {categories} = res.data;
            let arr = [];
            Array.from(_.get(categories,`[${menu.categoryIndex}].products`,[]));
            let categoryPicker = categories.map((item,index)=>{
                if(index == menu.categoryIndex){
                    arr = Array.from(item.products);
                    if(arr){
                        arr.push({})
                    }else{
                        arr = [{}]
                    }
                }
                return {
                    label:item.name,
                    value:item.server_category_id
                }
            })
            dispatch({
                type:TYPES.SETPRODUCTLIST,
                pruductlist:arr,
                categories:categories,
                categoryPicker:categoryPicker
            })
        }else{
            dispatch({
                type:TYPES.CHANGEPRODUCTLOADING,
                productload:false
            })
            dispatch(loadingAction(false));
            Toast.info(res.message,3,null,false);
        }
    })
    .catch((e)=>{
        console.log(e);
        dispatch({
            type:TYPES.CHANGEPRODUCTLOADING,
            productload:false
        })
    })
}

export function changeProductCategory(index){
    return (dispatch,getState)=>{
        let {productCategorys} = getState().menu;
        let arr = Array.from(_.get(productCategorys,`[${index}].products`));
        if(arr){
            arr.push({})
        }else{
            arr = [{}]
        }
        dispatch({
            type:TYPES.CHANGECATEGORYINDEX,
            categoryIndex:index,
            pruductlist:arr
        })
    }
}

export function deleteProduct(product,index){
    return (dispatch,getState)=>{
        Alert.alert(i18n.t("appName"),i18n.t("office.menu.deleteproduct"),[{
            text:i18n.t("btns.cancel"),
            },{
            text:i18n.t("btns.okText"),
            onPress:()=>{
                dispatch(loadingAction(true));
                http.post("productdelete",{product_id:product.server_product_id})
                .then((res)=>{
                    if(res.status){
                        _loadProduct(dispatch,getState,true);
                    }
                    toast(res.message);
                })
                .catch(e=>{
                    dispatch(loadingAction(false));
                    toast(i18n.t("net.neterror"))
                })
            }
        }])
    }
}

export function productInput(key,value){
    return (dispatch,getState)=>{
        let {showProduct} = getState().menu;
        showProduct[key] = value;
        dispatch({
            type:TYPES.SETSHOWPRODUCT,
            showProduct
        })
    }
}

export function setProductInfo(showProduct){
    return (dispatch,getState)=>{
        dispatch({
            type:TYPES.SETSHOWPRODUCT,
            showProduct
        })
    }
}

export function productOptionsInput(key,value){
    return (dispatch,getState)=>{
        let {productOptions} = getState().menu;
        productOptions[key] = value;
        dispatch({
            type:TYPES.SETPRODUCTOPTIONINFO,
            productOptions
        })
    }
}

export function setProducOption(productOptions){
    return (dispatch)=>{
        dispatch({
            type:TYPES.SETPRODUCTOPTIONINFO,
            productOptions
        })
    }
}

export function setDefaultProductInfo(){
    return (dispatch)=>{
        dispatch({
            type:TYPES.SETDEFAULTPRODUCTINFO,
        })
    }
}

export function inputProductOption(key,val){
    return (dispatch,getState)=>{
        let {productOption} = getState().menu;
        if(typeof key == "string"){
            productOption[key] = val;
        }else if(typeof key =='object'){
            productOption = key;
        }
        dispatch({
            type:TYPES.SETPRODEUCTOPTION,
            productOption
        })
    }
}

export function inputProductOptionValue(key,val){
    return (dispatch,getState)=>{
        let {productOptionValue} = getState().menu;
        if(typeof key == "string"){
            productOptionValue[key] = val;

        }else if(typeof key == 'object'){
            productOptionValue = key;
        }
        dispatch({
            type:TYPES.SETPRODUCTOPTIONVALUE,
            productOptionValue
        })
    }
}
const i18nName = i18n.t("office.menu.placeholderName"),
  i18nRequired = i18n.t("office.menu.required"),
  i18nMustbenum = i18n.t("office.menu.mustbenum"),
  i18nSpecialprice = i18n.t("office.menu.specialprice"),
  i18nSortOrder = i18n.t("office.menu.sortorder"),
  i18nPrice = i18n.t("office.menu.price"),
  i18nQty = i18n.t("office.menu.qty"),
  i18nReward = i18n.t("office.menu.rewardpoints");
export function saveProduct(cb){
    return (dispatch,getState,)=>{
        let {showProduct,categoryValue} = getState().menu;
        let body = Object.assign({},showProduct);
        let priceReg = /^([-+]?[0-9]+)(\.[0-9]{1,2})?$/;
        //edit
        if(body.server_product_id){
            body.product_id = body.server_product_id;
            delete body.server_product_id;
        }else if(body.path == null){
            return Toast.info(i18n.t("office.menu.selectpicture"),3,null,false);
        }
        if(!Array.isArray(body.categories) && body.categories.length < 1){
            return Toast.info(i18n.t("office.menu.selectcategory"),3,null,false);
        }
        body.category_id = body.categories[0];
        if(body.name == ""){
            return Toast.info(`${i18nName} ${i18nRequired}`,3,null,false);
        }
        if(body.price == "" || !priceReg.test(Number(body.price)) || Number(body.price) < 0){
            return Toast.info(`${i18nPrice} ${i18nMustbenum}`,3,null,false);
        }
        if(body.special_price == "" || !priceReg.test(Number(body.special_price))){
            return Toast.info(`${i18nSpecialprice} ${i18nMustbenum}`,3,null,false);
        }
        if(body.qty == "" || !/^\d+$/.test(Number(body.qty)) || Number(body.qty) < 0){
            return Toast.info(`${i18nQty} ${i18nMustbenum}`,3,null,false);
        }
        if(body.points == "" || !/^\d+$/.test(body.points)){
            return Toast.info(`${i18nPoint} ${i18nMustbenum}`,3,null,false);
        }
        
        if(body.path){
           let image_id = 0;
           if(Array.isArray(body.images) && body.images.length > 0){
                image_id = body.images[0].server_image_id;
           }
           body.images = [{
                source:body.path.image,
                sort_order:1
           }];
           if(image_id){
                body.images[0].image_id = image_id;
           }
           delete body.path;
        }else{
            body.images = []; 
        }
        delete body.date_added;
        body.options.map((item)=>{
            if(item.server_option_id){
                item.option_id = item.server_option_id;
                delete item.server_option_id; 
            }
            item.values.map(itemv=>{
                if(itemv.server_value_id){
                    itemv.value_id = itemv.server_value_id;
                    delete itemv.server_value_id;
                }
                if(Number(itemv.price)<0){
                    itemv["price_prefix"] = "-";
                }
                if(Number(itemv.points)<0){
                    itemv["points_prefix"] = "-";
                }
                return itemv;
            })
            return item;
        })
        console.log(JSON.stringify(body));
        body.version = body.version + 1;
        dispatch({
            type:TYPES.SETPRODUCTADDING,
            productadding:true
        })
        dispatch({
            type:TYPES.CHANGELOADING,
            loading:true
        })
        http.post("productsave",{
            data:JSON.stringify(body)
        })
        .then((res)=>{
            if(res.status){
                cb(true);
                dispatch({
                    type:TYPES.SETDEFAULTPRODUCTINFO,
                })
                dispatch({
                    type:TYPES.SETPRODUCTADDING,
                    productadding:false
                })
                _loadProduct(dispatch,getState,true);
            }else{
                cb(false);
                dispatch({
                    type:TYPES.SETPRODUCTADDING,
                    productadding:false
                })
                Toast.info(res.message,3,null,false);
            }
        })
        .catch((e)=>{
            console.log(e);
            cb(false);
            dispatch({
                type:TYPES.SETPRODUCTADDING,
                productadding:false
            })
            dispatch({
                type:TYPES.CHANGELOADING,
                loading:false
            })
        })
    }
}

export function setDetaultOption(){
    return (dispatch,getState)=>{
        dispatch({
            type:TYPES.SETDETAULTOPTION
        })
    }
}

export function setDetaultOptionValue(){
    return (dispatch,getState)=>{
        dispatch({
            type:TYPES.SETDETAULTOPTIONVALUE
        })
    }
}